為了取得 iPhone 裝置使用者的當前位置,我們首先必須先套用 Apple 的 CoreLocation 這個 library。
import CoreLocation
///並且對主要的 ViewController 進行 CLLocationManagerDelegate 的 subclass
ViewController: UIViewController, CLLocationManagerDelegate {
}
接著創造一個 locationManager
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//TODO:Set up the location manager here.
locationManager.delegate = self //宣告自己 (current VC)為 locationManager 的代理
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters //定位所在地的精確程度(一般來說,精準程度越高,定位時間越長,所耗費的電力也因此更多)
//to ask the user for location
locationManager.requestWhenInUseAuthorization() //for not destroying the user's battery
locationManager.startUpdatingLocation() //this method will start navigating the location. And once this is done, it will send a msg to this ViewController
}
接著,為了使請求定位權限的跳出視窗能夠順利在一打開 APP 時出現,我們必須回到 info.plist,添加這個彈出視窗的描述:
定義及管理定位方式:
定義定位方式:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//由於我們的 "startUpdatingLocation()" 會回傳一個陣列的 CLLocation ,而最後回傳的會是最接近於我們當前位置的 CLLocation 。 因此我們要娶的就是這個 CLLocation
let location = locations[locations.count - 1] //the method "startUpdatingLocation()" is gonna grab a set of locations that are getting more & more accurate. So we'd want the last location in this array
//簡單檢查一下取得的值
if location.horizontalAccuracy > 0 { //this line will check if the location is available
// 由於定位功能十分耗電,我們既然已經取得了位置,就該速速把它關掉
locationManager.stopUpdatingLocation()
print("latitude: \(location.coordinate.latitude), longtitude: \(location.coordinate.longitude)")
}
}
以及定義錯誤處理方式:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
cityLabel.text = "Location unavailable"
}